#/usr/bin/bash
INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/rocketmq"
fi

#ROCKETMQ架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/rocketmq/rocketmq-5.0.0/rocketmq-all-5.0.0-bin-release.zip
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/rocketmq/rocketmq-5.0.0/rocketmq-all-5.0.0-bin-release.zip"
fi

ROCKETMQ_PORT=$3
if [ ! $ROCKETMQ_PORT ];then
ROCKETMQ_PORT="9876"
fi


java -version

if [ $? -ne 0  ];then
	echo "--------------请先安装jdk,退出脚本------------"
	exit
fi


mvn -v 

if [ $? -ne 0 ];then
	 echo "--------------请先安装maven,退出脚本------------"
         exit
fi


##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH ];then
   mkdir $INSTALL_PATH
fi

cd $INSTALL_PATH

#wget下载文件
wget $DOWNLOAD_URL

echo ${FILENAME##*.}

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
	tar -zxvf $FILENAME -C $INSTALL_PATH
    else
	unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
fi

#删除安装包
rm -rf $INSTALL_PATH/$FILENAME

#获取解压后当前目录下的文件名
NEW_FILENAME=`ls -lt $INSTALLPATH |grep rocketmq-|head -n 1|awk '{print $9}'`;

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi


#进入rocketmq解压后的文件目录
cd $NEW_FILENAME/bin

#修改bin目录中 runserver.sh文件 和runbroker.sh文件 修改一下内存大小
sed -i "/^.*JAVA_OPT=\"\${JAVA_OPT} -server.*$/a  JAVA_OPT=\"\${JAVA_OPT} -server -Xms512m -Xmx512m -Xmn512m\"" runserver.sh
sed -i "N;/\n.*JAVA_OPT=\"\${JAVA_OPT} -server -Xms512m -Xmx512m -Xmn512m\"/!P;D" runserver.sh

sed -i "/^.*JAVA_OPT=\"\${JAVA_OPT} -server.*$/a  JAVA_OPT=\"\${JAVA_OPT} -server -Xms512m -Xmx512m -Xmn512m\"" runbroker.sh
sed -i "N;/\n.*JAVA_OPT=\"\${JAVA_OPT} -server -Xms512m -Xmx512m -Xmn512m\"/!P;D" runbroker.sh

#修改config目录下的配置文件
#获取公网ip
ip=`curl ident.me`

cd /usr/local/rocketmq/rocketmq-all-5.0.0-bin-release/conf
cat>>broker.conf<<EOF
namesrvAddr=$ip:$ROCKETMQ_PORT
brokerIp1=$ip
EOF

#启动mqnamesrv
cd $INSTALL_PATH
nohup sh $INSTALL_PATH/$NEW_FILENAME/bin/mqnamesrv &>mqnamesrv_start.log &

if [ $? -ne 0  ];then
	echo "-------------启动mqnamesrv失败，请前往$INSTALL_PATH下查看mqnamesrv_start.log日志信息------------"
	exit
fi

#启动broker
nohup sh $INSTALL_PATH/$NEW_FILENAME/bin/mqbroker -n $ip:$ROCKETMQ_PORT &>mqbroker_start.log &

if [ $? -ne 0  ];then
        echo "-------------启动broker失败，请前往$INSTALL_PATH下查看mqbroker_start.log日志信息------------"
        exit
fi

if [ $? -ne 0 ]; then
    echo "rocketmq启动失败，请排查原因，退出脚本";
    exit;
else
    echo "rocketmq 启动成功，请稍后手动登录云服务器,在安全组中放通$ROCKETMQ_PORT、10911、10912、10909端口";
fi
